<?php
include('../includes/classes/core.php');

$action	 = $_REQUEST['act'];
$user_id = $_SESSION['USERID'];
$error	 = '';
$error1	 ='';
$data	 = '';
switch ($action) {
	case 'show-seleced':
		$part		 = json_decode( '['.$_REQUEST['list'].']' );
		$page 		= ShowSelected($part);
		$data		= array('page'	=> $page);
		break;
	case 'get_workers':
		$status		= $_REQUEST['status'];
		$page 		= GetPage($status);
		$data		= array('page'	=> $page);

		break;
	case 'log-in':
		$user		= $_REQUEST['user'];
		$password	= $_REQUEST['password'];
		$answ		= check($user,$password);
		$data		= array('answ'	=> $answ);
		break;
	case 'get_part_list' :
		$barcode	= $_REQUEST['barcode'];
		$page 		= GetPartPage( $barcode );
		$data		= array('page'	=> $page);

		break;
	case 'get_worker_list' :
		$page 		= GetWorkerPage();
		$data		= array('page'	=> $page);

		break;
	case 'get_info_list' :
		$barcode	= $_REQUEST['barcode'];
		if($barcode != ""){
			$page 		= GetInfoPage($barcode);
		}else{
			$page 		= GetStaticInfoPage();
		}
		$data		= array('page'	=> $page);

		break;
	case 'get_history_list' :
		$barcode	= $_REQUEST['barcode'];
		if($barcode != ''){
			$page 		= GetHistoryPage($barcode);
		}else{
			$page 		= '';
		}
		$data		= array('page'	=> $page);
		break;
	case 'save_part' :
		$printerID = $_REQUEST['cartridgeID'];
		$part	     = $_REQUEST['list'];
		$part1	     = $_REQUEST['list1'];
		$barcode	 = $_REQUEST['barcode'];
		$person		 = $_REQUEST['person'];
		$wareHouseID = $_REQUEST['wareHouseID'];
		$type       = $_REQUEST['type'];
		//$type=false;		
		if($barcode != '' && strlen($barcode) == '15'){
		    if ($type==1) {
		        $error = SavePart($wareHouseID,$person,$part,$printerID,$barcode);
		    }else {
		        $error= SaveAltPart($wareHouseID,$person,[$part,$part1],$printerID,$barcode);
		    }

		}else{
			$error = 'შტრიხკოდი არასწორია';
		}
		;
		
		break;
	case 'get_servise':
		$clinet     = $_REQUEST['clinet'];
		$printer    = $_REQUEST['printer'];
		$page 		= GetServise($clinet, $printer);
		$data		= array('page'	=> $page);

		break;
	case 'reserve_takeoff':
		$part		 = json_decode( '['.$_REQUEST['list'].']' );
	//	print_r($part);
	//	$barcode     = $_REQUEST['barcode'];
	//	$printerID   = $_REQUEST['printerID'];
	//	$warehouseID = $_REQUEST['warehouseID'];
		//print_r
	//	ReserveTake($part, $printerID, $warehouseID,$barcode);
	//	$data['error1'] = $error1;

		break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);

function GetServise($clinet, $printer){
	$date = '';
	$rResult = mysql_query("SELECT	`printer_parts_type`.id,
									`printer_parts_type`.`name`,
									`printer_parts_type`.checked
							FROM	`printer_parts_type`
							WHERE	(`printer_parts_type`.`category` = 2 || `printer_parts_type`.`category` = 5 ) &&  `printer_parts_type`.actived != 0 
	    ORDER BY `printer_parts_type`.`name`");
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
			$data .= '	<tr class="trClass">
							<td class="tdClass">
									<table width="width: 200px;" >
										<tr>
											<td style="width : 20%"><img width="25px" height="25px" src="Administrator-icon.png" /></td>
											<td style="width: 200px;">'.$aRow[1].'</td>
										</tr>
											</table>
							</td>
							<td class="tdClass">';
			$data .= '	<input type="checkbox" id="checkbox2_'.$aRow[0].'" class="regular-checkbox2" value="'.$aRow[0].'" /><label for="checkbox2_'.$aRow[0].'"></label>';
			$data .= '		</td>
						</tr>';
	}
	return $data;
}

function GetPage($status){
	$rResult = mysql_query("SELECT DISTINCT `persons`.`name`
							FROM		`worker_action`
							RIGHT JOIN	`persons` ON `persons`.`id` = `worker_action`.`person_id`
							WHERE  `persons`.`p_active` =$status && `persons`.`actived` = 1 && `persons`.`position`= 17");
	$data = '';
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$data .= '<li class="users">'.$aRow[0].'</li>';
	}
	return $data;
}

function check($user,$password){

	$rResult = mysql_query("SELECT	`id`
							FROM	`persons`
							WHERE	`name` = '$user' && `password` = '$password'");
	$aRow = mysql_fetch_array( $rResult );
	if($aRow != ''){
		$c_data = date('Y-m-d H:i:s');
		$sqlResult = mysql_query("SELECT	`worker_action`.`id`
								  FROM		`persons`
								  LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
								  WHERE		`persons`.`p_active` = 1 && `persons`.`id` = $aRow[0] && ISNULL(`worker_action`.`end_date`)");
		$sqlResult = mysql_fetch_array( $sqlResult );
		if($sqlResult != ''){
			mysql_query("UPDATE `persons`
						SET		`p_active` = 0
						WHERE	`id` = $aRow[0]");

			mysql_query("UPDATE `worker_action`
						SET		`end_date` = '$c_data'
						WHERE	`id` = $sqlResult[0]");

		}else{
			mysql_query("INSERT	INTO	`worker_action`
							(person_id, start_date, work_type_id)
						VALUES
							($aRow[0],'$c_data','".$_REQUEST['worc_type']."')");
			mysql_query("UPDATE `persons`
						SET		`p_active` = 1
						WHERE	`id` = $aRow[0]");
		}
		return true;
	}else{
		return false;
	}
}

function GetPartPage($barcode){
	$data ='';
	if($barcode == ''){
		$rResult = mysql_query("SELECT		`printer_parts_type`.id,
											`printer_parts_type`.`name`,
											`printer_parts_type`.checked
								FROM		`printer_parts_type`
								WHERE		( `printer_parts_type`.`category` = 2 || `printer_parts_type`.`category` = 5 ) &&  `printer_parts_type`.actived != 0 
		                                     ORDER BY `printer_parts_type`.`name`
		    ");
	}else{
		$clientID  = (int) substr($barcode, 1, 4);
		$printerID = (int) substr($barcode, 5, 4);

		$rResult = mysql_query("SELECT		`printer_parts_type`.id,
											`printer_parts_type`.`name`,
											`printer_parts_type`.checked
								FROM		`printer_parts_type`
								WHERE		`printer_parts_type`.id in (
																			SELECT			`printer_pricelist`.`parts_type`
																			FROM			`client`
																			LEFT JOIN 		`printer_pricelist`   ON `printer_pricelist`.`client_id`   = `client`.`id`
																			WHERE			`printer_pricelist`.`production_id` = '$printerID' && `client`.`id` = '$clientID' AND printer_pricelist.actived=1
																		)
		    ORDER BY `printer_parts_type`.`name`");
	}
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$data .= '	<tr class="trClass">
						<td class="tdClass" id="clickID">
								<table width="width: 200px;" >
									<tr>
										<td style="display: none;" id="type">'.$aRow[0].'
										<td style="width : 20%"><img width="25px" height="25px" src="Administrator-icon.png" /></td>
										<td style="width: 200px;">'.$aRow[1].'</td>
									</tr>
								</table>
						</td>
						<td class="tdClass">';
		if($aRow[2] == '1'){
			$data .= '<input type="checkbox" id="checkbox_'.$aRow[0].'" class="regular-checkbox" value="'.$aRow[0].'" checked/><label for="checkbox_'.$aRow[0].'"></label>';
		}else{
			$data .= '<input type="checkbox" id="checkbox_'.$aRow[0].'" class="regular-checkbox" value="'.$aRow[0].'" /><label for="checkbox_'.$aRow[0].'"></label>';

		}
		$data .= '				</td>
					</tr>';
	}

	return $data;
}

function ShowSelected($part){
	$data ='';
	foreach($part as $partID) {
		$rResult = mysql_query("SELECT		`printer_parts_type`.id,
											`printer_parts_type`.`name`
								FROM		`printer_parts_type`
								WHERE		`printer_parts_type`.id = '$partID'");
		$aRow = mysql_fetch_array( $rResult );
		$data .= '	<tr class="trClass">
						<td class="tdClass">
								<table width="width: 200px;" >
									<tr>
										<td style="width : 20%"><img width="25px" height="25px" src="Administrator-icon.png" /></td>
										<td style="width: 200px;">'.$aRow[1].'</td>
									</tr>
								</table>
						</td>
						<td class="tdClass">';
		$data .= '<input type="checkbox" id="checkbox1_'.$aRow[0].'" class="regular-checkbox1" value="'.$aRow[0].'" checked/><label for="checkbox1_'.$aRow[0].'"></label>';

		$data .= '				</td>
					</tr>';

	}
	return $data;
}

function GetWorkerPage(){
	$data = '';
	$rResult = mysql_query("SELECT	DISTINCT `persons`.`id`,
									`persons`.`name`,
									`persons`.`image`
							FROM		`persons`
							LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
							WHERE `persons`.`p_active` = 1 && `persons`.`actived` = 1 && `persons`.`position`= 17");

	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		if($aRow[2] == ''){
			$aRow[2] ='0.jpg';
		}
		$data .= '
				    <tr>
						<td style="vertical-align: top; " >
					    	<button class="button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="'.$aRow[0].'" id="'.$aRow[0].'">
								<table width="180px" >
									<tr>
										<td style="width : 20%"><img width="25px" height="25px" src="../media/uploads/images/worker/'.$aRow[2].'" /></td>
										<td style="width : 80% ">'.$aRow[1].'</td>
									</tr>
								</table>
							</button>
					    </td>
					</tr>';
	}
	return $data;
}

function GetInfoPage($barcode){
	$rResult = mysql_query("SELECT		`warehouse_detail`.`barcode` ,
										`production`.`name`,
										CONCAT(`client`.`name`,'(',`client_objects`.`name`, ')'),
										`warehouse_detail`.`id`,
										`production`.`id`,
										`client`.`id`,
										barcodes.serial_number,
										warehouse_detail.`comment` as coment
										FROM		`warehouse`
										LEFT JOIN 	( `warehouse_detail` LEFT JOIN `production` ON `production`.`id` = `warehouse_detail`.`prod_id` )ON `warehouse_detail`.`warehouse_id` = `warehouse`.`id`
										LEFT JOIN 	( `client_objects` LEFT JOIN `client` ON `client`.`id` = `client_objects`.`client_id` ) ON `client_objects`.`id` = `warehouse`.`client_object_id`
										LEFT JOIN   `barcodes` ON `barcodes`.`code`=warehouse_detail.barcode AND barcodes.actived=1
										WHERE 		 `warehouse_detail`.`barcode` = '$barcode' AND warehouse_detail.actived=1
										ORDER BY 	 `warehouse`.`start_date` DESC
										LIMIT 1");
	$aRow = mysql_fetch_array( $rResult );
	if($aRow != ''){
		$data ='
		<tr>
			<td>
				<label for="barcode">შტრიხკოდი : </label> '.$aRow[0].'
			</td>
		</tr>
		<tr>
			<td>
				<label for="cartridge">კატრიჯი : </label> '.$aRow[1].'
			</td>
		</tr>
		<tr >
			<td>
				<label for="client_object">კლიენტი : </label> '.$aRow[2].'
			</td>
		</tr>
		<tr >
			<td>
				<label for="client_object">სერიული N: </label> '.$aRow[6].'
		</td>
		</tr>
								<tr >
		<td>
				<label for="client_object">კომენტარი: </label> '.$aRow[coment].'
		</td>
		</tr>
		<tr style="display: none;">
			<td>
				<input type="" id="warehouseID" value="' .$aRow[3]. '"/>
			</td>
		</tr>
		<tr style="display: none ;">
			<td>
				<input type="" id="printerID" value="' .$aRow[4]. '"/>
			</td>
		</tr>
		<tr style="display: none;">
			<td>
				<input type="" id="clientID" value="' .$aRow[5]. '"/>
			</td>
		</tr>';
		return $data;
	}else{
		global $error;
		$error = 'შტრიხკოდი არასწორია';
		$data  = GetStaticInfoPage();
		return $data;
	}
}
function GetStaticInfoPage(){
	$data ='
		<tr>
			<td>
				<label for="barcode">შტრიხკოდი : </label>
			</td>
		</tr>
		<tr>
			<td>
				<label for="cartridge">პრინტერ : </label>
			</td>
		</tr>
		<tr>
			<td>
				<label for="client_object">კლიენტი : </label>
			</td>
		</tr>
		<tr>
			<td>
				<label for="client_object">სერიული : </label>
			</td>
		</tr>';

	return $data;
}
function GetHistoryPage($barcode){
	$rResult = mysql_query("SELECT		printer_parts_type.`name`,
										'1' AS count,
										DATE(warehouse_producing.date) as date
							FROM		`warehouse_producing`
							LEFT JOIN   warehouse_detail ON warehouse_detail.id = warehouse_producing.warehouse_detail_id
							LEFT JOIN   printer_parts_type ON printer_parts_type.id = warehouse_producing.printer_part_id
							WHERE		warehouse_detail.barcode = '$barcode' &&  ( `printer_parts_type`.`category` = 2 || `printer_parts_type`.`category` = 5 ) AND warehouse_detail.actived=1
							ORDER BY warehouse_producing.id DESC");

	$rResult1 = mysql_query("SELECT		printer_parts_type.`name`,
                            			'1' AS count,
                            			DATE(real_history.date) as date
                            FROM		`real_history`
                            LEFT JOIN   printer_parts_type ON printer_parts_type.id = real_history.printer_part_id
                            WHERE		real_history.barcode = '$barcode'
                            ORDER BY real_history.id DESC");
	while ( $aRow1 = mysql_fetch_array( $rResult1 ) )
	{
	    $data .= '	<tr  class="trClass">
						<td class="tdClass" style="background: rgba(0, 255, 3, 0.2);">'.$aRow1[0].'</td>
						<td class="tdClass" style="background: rgba(0, 255, 3, 0.2);">'.$aRow1[1].'</td>
						<td class="tdClass" style="background: rgba(0, 255, 3, 0.2);">'.$aRow1[2].'</td>
					</tr>';
	}
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$data .= '	<tr class="trClass">
						<td class="tdClass">'.$aRow[0].'</td>
						<td class="tdClass">'.$aRow[1].'</td>
						<td class="tdClass">'.$aRow[2].'</td>
					</tr>';
	}

	return $data;

}

function SavePart($wareHouseID,$person,$part,$printerID,$barcode){ 
    $error=''; 
   $query=mysql_query("
SELECT  printer_parts_type.`name`,
        printer_parts_type.`id` AS part_id,
        printer_parts_type.category AS part_type_category,
		prod.qv AS qv,        
		prod.`name` as prod_name,
        prod.id AS prod_id		
FROM   printer_parts_type
LEFT JOIN (
        SELECT 	quantity-sold AS qv, 
        		parts_type,
                production.id,
        		production.`name`
        FROM printer_identity
        JOIN production_category ON printer_identity.parts_category=production_category.id AND production_category.actived=1
        JOIN production ON production.category=production_category.id AND production.actived=1
        JOIN reserve ON reserve.production_id=production.id AND quantity - sold >0 AND object_id=154
        WHERE printer_identity.production_id=$printerID AND parts_type IN ($part) 
        ) AS prod ON prod.parts_type in (printer_parts_type.id)
WHERE  printer_parts_type.id IN($part)
");
                   
    while ($row = mysql_fetch_array($query)) {
        $cat[]=$row;
        if ($row[qv]<=0 & $row[part_type_category]==2) {
            $error.="\n $row[name] -ს ნაწილი ვერ მოიძებნა მარაგში";
        }
    }
   
    if ($error!='') {
        return  $error;
    }else{       
        foreach ($cat as $cat1){
            InsertPart($person,$wareHouseID,$cat1[part_id],$cat1[prod_id]);
            ReserveTakeOff($cat1[prod_id],1,154);
        }   
    return "ყველა ოპერაცია წარმატებით განხორციელდა!";} ;
    
        
 
}
function SaveAltPart($wareHouseID,$person,$part,$printerID,$barcode,$type){
    $error='';
    $query=mysql_query("
SELECT  printer_parts_type.`name`,
        printer_parts_type.`id` AS part_id,
        printer_parts_type.category AS part_type_category,
        prod.qv AS qv,
        prod.`name` as prod_name,
        prod.id AS prod_id
        FROM   printer_parts_type
        LEFT JOIN (
        SELECT 	quantity-sold AS qv,
        parts_type,
        production.id,
        production.`name`
        FROM printer_identity
        JOIN production_category ON printer_identity.parts_category=production_category.id AND production_category.actived=1
        JOIN production ON production.category=production_category.id AND production.actived=1
        JOIN reserve ON reserve.production_id=production.id AND quantity - sold >0 AND object_id=154
        WHERE printer_identity.production_id=$printerID
        ) AS prod ON prod.parts_type in (printer_parts_type.id)
        WHERE  printer_parts_type.id IN($part[1])
        "); 
    while ($row = mysql_fetch_array($query)) {
        $cat[]=$row;
        if ($row[qv]<=0 & $row[part_type_category]==2) {
            $error.="\n $row[name]-ს ნაწილი ვერ მოიძებნა მარაგში";
        }
    }
     
    if ($error!='') {
        return  $error;
    }else{
        foreach ($cat as $cat1){
           
            if ( ReserveTake($cat1[1], $printerID, $wareHouseID, $barcode,$cat1[prod_id])) {
               
                ReserveTakeOff($cat1[prod_id],1,154);
            }  else{
                
            } 
                        
           
        }
   

        $part68 =  preg_split("/[,]+/",$part[0]);
        foreach ($part68 as $cat1){       
            InsertPart($person,$wareHouseID,$cat1);
          
        }
     
        
        return "ყველა ოპერაცია წარმატებით განხორციელდა!";} ;
 
}
function InsertPart($person,$wareHouseID,$partID,$productionID = '0'){

	$rResult1 = mysql_query("SELECT		`id`
							 FROM		`warehouse_producing`
							 WHERE		`warehouse_producing`.`warehouse_detail_id` = $wareHouseID && `warehouse_producing`.`printer_part_id` = $partID
							 ORDER BY	`warehouse_producing`.`id` DESC
							 LIMIT 1");

	$aRow = mysql_fetch_array($rResult1);

	if( $aRow == ''){
		$c_data = date('Y-m-d H:i:s');
		mysql_query("INSERT INTO	`warehouse_producing`
						(`person_id`,`warehouse_detail_id`,`printer_part_id`,`production_id`,`date`)
					VALUES
						($person,$wareHouseID,$partID,'$productionID','$c_data')");
	}else{
		$c_data = date('Y-m-d H:i:s');
		mysql_query("UPDATE		`warehouse_producing`
					 SET		`warehouse_producing`.`date` = '$c_data',
					 			`warehouse_producing`.production_id = $productionID
					 WHERE		`warehouse_producing`.`id` = $aRow[0]");
	}
}

function ReserveTakeOff($prod_id, $quantity, $object)
{
	$req_quantity = $quantity;
	$res = mysql_query("SELECT  `reserve`.`id`,
								`reserve`.`production_id`,
								`reserve`.`object_id`,
								`reserve`.`sold`,
								`reserve`.`quantity` - `reserve`.`sold` AS `diff`,
								`reserve`.`create_date`
						FROM `reserve`
						WHERE `reserve`.`object_id` = $object && `reserve`.`production_id` = $prod_id
						ORDER BY `reserve`.`create_date` ASC" );
	while ($row = mysql_fetch_array($res)) {
		if ($req_quantity != 0) {
			if($row['diff'] > $req_quantity){
				$sum = $row['sold'] + $req_quantity;
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else if($row['diff'] == $req_quantity){
				$sum = $row['sold'] + $row['diff'];
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else{
				$sum = $row['sold'] + $row['diff'];
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = $req_quantity - $row['diff'];
			}
		}
	}
}
function ReserveTake($part, $printerID, $warehouseID, $barcode,$prod_id){
   $sql=mysql_query("SELECT *
        FROM real_history
        WHERE 
        `barcode`='$barcode'AND 
        `printer_part_id`='$part' AND 
        `production_id`='$printerID' AND 
        `part_prod_id`='$prod_id' AND
        `warehouse_id`='$warehouseID'");
   if (mysql_num_rows($sql)>0)  return  false;
 
    $sql=mysql_query("INSERT INTO `real_history` 
	        (`barcode`,  `printer_part_id`, `production_id`, `date`, `warehouse_id`, part_prod_id) 
	 VALUES ('$barcode', '$part',           '$printerID',     NOW(), '$warehouseID', '$prod_id')");
    return true;
	
}

?>